﻿#include "app.h"
#include <QSettings>

QString App::ConfigFile     =   "config.ini";
QString App::ServerIP       =   "10.240.50.120";
QString App::ServerPort     =   "8101";

void App::readConfig()
{
    if (!checkConfig()) {
        return;
    }

    QSettings set(App::ConfigFile, QSettings::IniFormat);

    set.beginGroup("ServerConfig");

    App::ServerIP = set.value("ServerIP").toString();
    App::ServerPort = set.value("ServerPort").toString();

    set.endGroup();
}

void App::writeConfig()
{
    QSettings set(App::ConfigFile, QSettings::IniFormat);

    set.beginGroup("ServerConfig");

    set.setValue("ServerIP", App::ServerIP);
    set.setValue("ServerPort", App::ServerPort);
    set.endGroup();

}

void App::newConfig()
{
    writeConfig ();
}

bool App::checkConfig()
{
    //如果配置文件大小为0,则以初始值继续运行,并生成配置文件
    QFile file(App::ConfigFile);
    if (file.size() == 0) {
        newConfig();
        return false;
    }

    //如果配置文件不完整,则以初始值继续运行,并生成配置文件
    if (file.open(QFile::ReadOnly)) {
        bool ok = true;
        while (!file.atEnd()) {
            QString line = file.readLine();
            line = line.replace("\r", "");
            line = line.replace("\n", "");
            QStringList list = line.split("=");

            if (list.count() == 2) {
                if (list.at(1) == "") {
                    ok = false;
                    break;
                }
            }
        }

        if (!ok) {
            newConfig();
            return false;
        }
    } else {
        newConfig();
        return false;
    }

    return true;
}
